<?php

declare(ENCODING = 'UTF-8');

/*                                                                        *
 * This script is part of the TYPO3 project - inspiring people to share!  *
 *                                                                        *
 * TYPO3 is free software; you can redistribute it and/or modify it under *
 * the terms of the GNU General Public License version 2 as published by  *
 * the Free Software Foundation.                                          *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *	
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General      *
 * Public License for more details.                                       *
 *                                                                        */	

/**
 * @package auxo
 * @subpackage core
 * @version $Id$
 */

/**	
 * A simple Hash Array Class
 * 
 * This class implements a hash array. It allows to add objects or data uniquely to an array. 
 * Keys are generated automatically using a hash method. Hash arrays could be used in the same
 * way as PHP default arrays because this class implements the interator and countable 
 * interface. 
 *	
 * @package auxo
 * @subpackage core	
 * @version $Id$	
 * @copyright Copyright belongs to the respective authors
 * @author AHN
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License, version 2
 */
class  tx_auxo_HashArray implements Iterator, Countable {
	
	private $storage = array();
	
	private $index = 0;
 
	public function __construct($values=NULL) {
		if (isset($values)) {
			foreach($values as $value) {
				$this->add($value);	
			}
		}
	}
	
	public function rewind() {
   		rewind($this->storage);
	}

	public function valid() {
   		return key($this->storage) !== false;
	}

	public function key() {
		return $this->index;
	}

	public function current() {
		return current($this->storage);
	}

	public function next() {
		next($this->storage);
		$this->index++;
	}

	public function count() {
		return count($this->storage);
	}

	/**
	 * adds a value to the hash
	 *
	 * @param mixed $value
	 * @return string $key
	 */
	public function add($value) {
		$this->storage[$key = $this->getHashKey($value)] = $value;
		return $key;
	}
	
	public function remove($value) {
		if ($this->has($value))	unset($this->storage[$this->getHashKey($value)]);		
	}
	
	public function has($value) {
		return isset($this->storage[$this->getHashKey($value)]);
	}
	
	public function getHashKey($value) {
		if (is_object($value)) {
			$key = spl_object_hash($value);
		}
		else {
			$key = md5($value);
		}		
		return $key;
	}
}
?>